<template>
  <div
    class="sphere-viewer"
    @contextmenu.prevent='()=>false'
    ref="sphereViewer"
  >
    <edit-tooltilp
      :dialogFormVisible=dialogFormVisible
      :markerFormName=markerFormName
      :markerFormDesc=markerFormDesc
      @editTooltilpClose="editTooltilpClose"
      @confirm="confirm"
      @markerDel="markerDel"
    ></edit-tooltilp>
    <div class="sphere-viewer-close">
      <el-button
        size="mini"
        @click="edit()"
        :type="editState?'success':'primary'"
      >{{editState?'保存':'编辑'}}</el-button>
      <el-button
        size="mini"
        @click="close()"
      >关闭</el-button>
    </div>
    <div class="viewer-container">
      <div class="container">
        <div
          class="headerInfo"
          @mousedown="drag"
        >
          <div class="title">主全景</div>
          <el-select
            v-model="value_1"
            placeholder="请选择"
            @change="change(value_1,value_2,'1')"
            size="mini"
            :disabled="editState"
          >
            <el-option
              v-for="item in panorama"
              :key="item.date"
              :label="item.date"
              :value="item.date"
            >
            </el-option>
          </el-select>
        </div>
        <div
          id="viewer_1"
          @mousemove="mousemove"
          @contextmenu.prevent='()=>false'
        >
        </div>
        <div
          class="tool-wrap"
          v-show="editState"
        >
          <el-button
            size="mini"
            @click="startDrawMark(0,'view_1')"
          >标注</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(1,'view_1')"
          >线</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(2,'view_1')"
          >面</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(3,'view_1')"
          >圆</el-button>
        </div>
      </div>
      <div class="container">
        <div
          class="headerInfo"
          @mousedown="drag"
        >
          <div class="title">侧全景</div>
          <el-select
            v-model="value_2"
            placeholder="请选择"
            @change="change(value_1,value_2,'2')"
            size="mini"
            :disabled="editState"
          >
            <el-option
              v-for="item in panorama"
              :key="item.date"
              :label="item.date"
              :value="item.date"
            >
            </el-option>
          </el-select>
        </div>
        <div
          id="viewer_2"
          @mousemove="mousemove"
          @contextmenu.prevent='()=>false'
        >
        </div>
        <div
          class="tool-wrap"
          v-show="editState"
        >
          <el-button
            size="mini"
            @click="startDrawMark(0,'view_2')"
          >标注</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(1,'view_2')"
          >线</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(2,'view_2')"
          >面</el-button>
          <el-button
            size="mini"
            @click="startDrawMark(3,'view_2')"
          >圆</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import localStorage from 'psvJs/storage.js'
import PhotoSphereViewer from 'PhotoSphereViewer'
import EditTooltilp from './editTooltilp.vue'
import MarkerDraw from 'psvJs/draw.js'
import { getPanoramaData, markerData } from 'api/getData'
import { saveAs } from 'file-saver'
import { INDEX_VIEW } from 'utils/constants'
const imgUrl1 = require('assets/images/pin1.png')
const imgUrl2 = require('assets/images/pin2.png')
const imgUrl3 = require('assets/images/pin3.png')
export default {
  name: 'SphereViewer',
  data() {
    return {
      markerFormName: '',
      markerFormDesc: '',
      editState: false,
      dialogFormVisible: false,
      panorama: [], // 缓存全景数据
      value_1: '', // 主全景日期
      value_2: '', // 侧全景日期
      markerImgArr: [imgUrl1, imgUrl2, imgUrl3] // 图标数组
      // markerDraw: new MarkerDraw() // 绘制类
    }
  },
  mounted() {
    setTimeout(() => {
      this.createViewer()
    }, 20)
  },
  props: {
    panoramaId: {
      type: String,
      default: ''
    }
  },
  methods: {
    drag(e) { // 窗口拖动
      // 获取sphereViewer左上角的屏幕位置
      let sphereViewer = this.$refs.sphereViewer
      // let sphereLeft = Number(sphereViewer.style.left.split('p')[0])
      // let sphereTop = Number(sphereViewer.style.top.split('p')[0])
      let sphereLeft = sphereViewer.offsetLeft
      let sphereTop = sphereViewer.offsetTop
      // 获取鼠标按下时，鼠标的屏幕位置和sphereViewer左上角的屏幕位置的差值
      let disX = e.clientX - sphereLeft
      let disY = e.clientY - sphereTop
      // console.log(sphereViewer.offsetLeft, sphereViewer.offsetTop)
      document.onmousemove = (e) => { // 鼠标按下并移动的事件
        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX
        let top = e.clientY - disY
        // 移动当前元素
        // console.log(e.clientX, e.clientY)
        sphereViewer.style.top = top + 'px'
        sphereViewer.style.left = left + 'px'
      }
      document.onmouseup = (e) => {
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    createViewer() { // 创建两个全景实例
      this.PSV = new PhotoSphereViewer({
        container: 'viewer_1',
        // autoload: true,
        loading_img: './site/images/photosphere-logo.gif',
        caption: `日期：`,
        panorama: '',
        min_fov: 15,
        max_fov: 90,
        anim_speed: '-2rpm',
        time_anim: false,
        // size: { width: 768, height: 500 },
        // latitude_range: [-Math.PI * 3 / 4, 0],
        navbar: [
          'autorotate',
          'zoom',
          'markers',
          'stereo',
          'caption',
          'gyroscope'
          // 'fullscreen'
        ]
        // ready: true
      })
      this.PSV.hideNavbar()
      this.PSV_sub = new PhotoSphereViewer({
        container: 'viewer_2',
        loading_img: './site/images/photosphere-logo.gif',
        caption: `日期：`,
        panorama: '',
        min_fov: 15,
        max_fov: 90,
        anim_speed: '-2rpm',
        time_anim: false,
        // size: { width: 768, height: 500 },
        // latitude_range: [-Math.PI * 3 / 4, 0],
        navbar: [
          'autorotate',
          'zoom',
          'markers',
          'stereo',
          'caption',
          'gyroscope'
          // 'fullscreen'
        ]
      })
      this.PSV_sub.hideNavbar()
      this.psvEvent()
    },
    psvEvent() { // 事件绑定
      this.PSV.on('position-updated', position => { // 双屏同步
        if (this.PSV_sub && this.PSV.m_rotation) { // 添加一个私有变量
          const P = this.PSV_sub.getPosition()
          const longitude = P.longitude - this.PSV.m_rotation.longitude
          const latitude = P.latitude + this.PSV.m_rotation.latitude
          const P_rotate = {
            longitude: longitude,
            latitude: latitude
          }
          this.PSV_sub.rotate(P_rotate)
        }
      })
      this.PSV.on('zoom-updated', zoom => { // 双屏同步
        // console.log(zoom)
        // if (MarkerDraw.currentMark.psvMarker) {
        //   console.log(MarkerDraw.currentMark.psvMarker.getScale(zoom))
        // }
        if (this.PSV_sub) {
          this.PSV_sub.zoom(zoom)
        }
      })
      this.PSV.on('select-marker', (marker, click) => { // 点击获取mark
        if (this.editState && (!MarkerDraw.currentMark.psvMarker) && (!MarkerDraw.currentMark._objCache)) {
          marker.content = null
          const cacheMarker = MarkerDraw.cacheMarkerView_1.find((value) => {
            return value.id === marker.id
          })
          this.markerFormName = marker.data.name
          this.markerFormDesc = marker.data.desc
          MarkerDraw.currentMark.psvMarker = marker
          MarkerDraw.currentMark._objCache = cacheMarker
          MarkerDraw.currentMark._currentView = 'view_1'
          this.editTooltip()
        }
      })
      this.PSV_sub.on('select-marker', (marker, click) => { // 点击获取mark
        if (this.editState && (!MarkerDraw.currentMark.psvMarker) && (!MarkerDraw.currentMark._objCache)) {
          marker.content = null
          const cacheMarker = MarkerDraw.cacheMarkerView_2.find((value) => {
            return value.id === marker.id
          })
          this.markerFormName = marker.data.name
          this.markerFormDesc = marker.data.desc
          MarkerDraw.currentMark.psvMarker = marker
          MarkerDraw.currentMark._objCache = cacheMarker
          MarkerDraw.currentMark._currentView = 'view_2'
          console.log(MarkerDraw.currentMark.psvMarker)
          this.editTooltip()
        }
      })
      this.PSV.on('click', evt => {
        if (MarkerDraw.currentMark._startDraw && !INDEX_VIEW[MarkerDraw.currentMark._currentView]) this.draw(evt)
      })
      this.PSV_sub.on('click', evt => {
        if (MarkerDraw.currentMark._startDraw && INDEX_VIEW[MarkerDraw.currentMark._currentView]) this.draw(evt)
      })
    },
    loadMarker(viewerNum) { // 初始化标注 viewerNum全景viewer编号（主全景为1，侧全景为2）
      // console.log('初始化标注')
      if (viewerNum === '1') {
        // 用于主全景标注的绘制
        if (this.mark_1.length === 0) return
        this.mark_1.forEach(data => {
          MarkerDraw.loadMarker(MarkerDraw.cacheMarkerView_1, data, this.PSV)
          // const option = data.option
          // const mark = {
          //   id: data.id,
          //   _option: {
          //     'tooltip': option.tooltip || '',
          //     'scale': option.scale || '',
          //     'circle': option.circle || '',
          //     'fill': option.fill || '',
          //     'stroke': option.stroke || '',
          //     'strokeWidth': option.strokeWidth || '',
          //     'image': this.markerImgArr[option.image] || ''
          //   }
          // }
          // MarkerDraw[data.type](data.pos, mark, this.PSV)
        })
      }
      if (viewerNum === '2') {
        if (this.mark_2.length === 0) return
        this.mark_2.forEach(data => {
          MarkerDraw.loadMarker(MarkerDraw.cacheMarkerView_2, data, this.PSV_sub)
        })
      }
    },
    close() { // 关闭全景
      if (this.editState) return
      this.$emit('close')
    },
    edit() {
      this.editState = !this.editState
      if (!this.editState) {
        const data = {
          'code': '200',
          'mark_1': {
            'id': '1',
            'data': MarkerDraw.cacheMarkerView_1
          },
          'mark_2': {
            'id': '2',
            'data': MarkerDraw.cacheMarkerView_2
          }
        }
        // 导出json文件 // 新增
        const flag = confirm('下载json')
        if (flag) {
          const blob = new Blob([JSON.stringify(data)], { type: '' })
          saveAs(blob, this.markerDataName)
        }
        const obj = {
          marker1: MarkerDraw.cacheMarkerView_1,
          marker2: MarkerDraw.cacheMarkerView_2
        }
        localStorage.save(obj, `markID${this.markID}`)
        // console.log(this.markerDataName)
        // // 导出json文件
        // const blob = new Blob([JSON.stringify(data)], { type: '' })
        // saveAs(blob, this.markerDataName)
      }
    },
    draw(evt) { // 全景绘制事件绑定
      if (INDEX_VIEW[MarkerDraw.currentMark._currentView]) { // 0为主全景 1为侧全景
        MarkerDraw.drawMark(evt, this.PSV_sub)
      } else {
        MarkerDraw.drawMark(evt, this.PSV)
      }
    },
    startDrawMark(index, indexView) { // 选择绘制图形的类别
      if (this.editState) { // 开启编辑状态
        this.mark(index, indexView)
        if (INDEX_VIEW[MarkerDraw.currentMark._currentView]) { // 0为主全景 1为侧全景
          this.PSV_sub.hud.container.style.cursor = 'pointer'
        } else {
          this.PSV.hud.container.style.cursor = 'pointer'
        }
      }
    },
    mark(indexMarker, indexView) { // 缓存当前绘制图形
      // 传入配置
      this.option = {
        image: this.markerImgArr[1]
      }
      if (INDEX_VIEW[indexView]) {
        this.option.stroke = 'rgba(232, 186, 23, 0.8)'
      }
      MarkerDraw.initCurrentMark(indexMarker, indexView, this.option, this.editTooltip)
    },
    editTooltip() {
      this.dialogFormVisible = true
    },
    editTooltilpClose(updateMarkerObj = {}) {
      this.dialogFormVisible = false
      MarkerDraw.updateMarker(updateMarkerObj) // 更新标注属性后 绘制类内部会将当前标注点等于{}
    },
    markerDel() {
      if (INDEX_VIEW[MarkerDraw.currentMark._currentView]) {
        MarkerDraw.removeMarker(MarkerDraw.cacheMarkerView_2, MarkerDraw.currentMark.psvMarker, this.PSV_sub)
      } else {
        MarkerDraw.removeMarker(MarkerDraw.cacheMarkerView_1, MarkerDraw.currentMark.psvMarker, this.PSV)
      }
      this.editTooltilpClose()
    },
    confirm(name, desc) {
      const content = (name || desc) ? `<h1 style='color:#eee;font-size: 1.5em;margin:10px 0;'>${name}</h1>
          <p><strong>${desc}</strong></p>` : ''
      const updateMarkerObj = {
        content: content,
        data: {
          name: name,
          desc: desc
        }
      }
      this.editTooltilpClose(updateMarkerObj)
    },
    mousemove(evt) { // 绘制时鼠标移动绘制
      if ((!this.PSV) || (!this.PSV_sub)) return
      if (!(MarkerDraw.currentMark._type === 'Circle')) return
      const PSV = INDEX_VIEW[MarkerDraw.currentMark._currentView] ? this.PSV_sub : this.PSV
      const boundingRect = PSV.container.getBoundingClientRect()
      const data = {
        type: evt.type,
        target: evt.target,
        client_x: evt.clientX,
        client_y: evt.clientY,
        viewer_x: parseInt(evt.clientX - boundingRect.left),
        viewer_y: parseInt(evt.clientY - boundingRect.top)
      }
      const intersect = PSV.viewerCoordsToVector3({ x: data.viewer_x, y: data.viewer_y })
      if (intersect) {
        const sphericalCoords = PSV.vector3ToSphericalCoords(intersect)
        data.longitude = sphericalCoords.longitude
        data.latitude = sphericalCoords.latitude
      }
      MarkerDraw.drawMark(data, PSV)
    },
    getPanoramaData(id) { // 获取全景数据
      getPanoramaData(id).then(res => {
        console.log(res.panorama.data)
        // res.panorama.data.forEach(data => {
        // })
        this.panorama = res.panorama.data
        this.value_1 = this.panorama[0].date // 主全景的时间
        this.value_2 = this.panorama[1] ? this.panorama[1].date : this.panorama[0].date // 侧全景的时间
        this.change(this.value_1, this.value_2, '0')
      }).catch(err => {
        console.log(err)
      })
    },
    change(date_1, date_2, selectNum) { // 切换全景数据时加载 带个id
      if (this.editState) return // 如果是编辑状态则不能切换全景
      this.PSV.clearMarkers()
      this.PSV_sub.clearMarkers()
      // 获取选中日期的索引
      let index_1 = 0
      let index_2 = 0
      if (selectNum === '1') {
        index_1 = this.panorama.findIndex((value) => {
          return value.date === date_1
        })
        console.log(index_1)
        if (index_1 === this.panorama.length - 1) {
          index_2 = index_1
          console.log('已是最早一期')
        } else {
          index_2 = index_1 + 1
        }
        this.value_2 = this.panorama[index_2].date
      } else {
        index_1 = this.panorama.findIndex((value) => {
          return value.date === date_1
        })
        index_2 = this.panorama.findIndex((value) => {
          return value.date === date_2
        })
      }
      // /** id测试
      let id = '01'
      if (index_1 < index_2) {
        id = `${this.panoramaId}${index_1}${index_2}`
      } else {
        id = `${this.panoramaId}${index_2}${index_1}`
      }
      //  */
      // 通过时间查找索引
      console.log(id)
      this.markID = id // 新增
      this.markerDataName = `markerData${id}.json`
      markerData(id).then(res => {
        // 新增
        const localMark_1 = localStorage.fetch(`markID${id}`).marker1 // 新增
        const localMark_2 = localStorage.fetch(`markID${id}`).marker2 // 新增
        if (localMark_1 && localMark_1.length > 0) {
          const obj = {}
          console.log(res.mark_1.data.concat(localMark_1))
          this.mark_1 = res.mark_1.data.concat(localMark_1).reduce((cur, next) => {
            if (!obj[next.id]) {
              obj[next.id] = true
            } else {
              cur.push(next)
            }
            return cur
          }, [])
          console.log(obj)
        } else {
          this.mark_1 = res.mark_1.data // 用于主全景标注的绘制
        }
        if (localMark_2 && localMark_2.length > 0) {
          const obj = {}
          this.mark_2 = res.mark_2.data.concat(localMark_2).reduce((cur, next) => {
            if (!obj[next.id]) {
              obj[next.id] = true
            } else {
              cur.push(next)
            }
            return cur
          }, [])
        } else {
          this.mark_2 = res.mark_2.data // 用于侧全景标注的绘制
        }
        // 新增
        // this.mark_1 = res.mark_1.data // 用于主全景标注的绘制
        // this.mark_2 = res.mark_2.data // 用于侧全景标注的绘制
        if (selectNum === '0') { // selectNum选择框序号
          this.PSV.setPanorama(this.panorama[index_1].url, this.panorama[index_1].target)
            .then(() => {
              this.PSV.setCaption(this.panorama[index_1].date)
              this.loadMarker('1')
            })
          this.PSV_sub.setPanorama(this.panorama[index_2].url, this.panorama[index_2].target)
            .then(() => {
              this.PSV_sub.setCaption(this.panorama[index_2].date)
              this.loadMarker('2')
            })
        }
        if (selectNum === '1') {
          this.PSV.setPanorama(this.panorama[index_1].url, this.panorama[index_1].target)
            .then(() => {
              this.PSV.setCaption(this.panorama[index_1].date)
              this.loadMarker('1')
            })
          this.PSV_sub.setPanorama(this.panorama[index_2].url, this.panorama[index_2].target)
            .then(() => {
              this.PSV_sub.setCaption(this.panorama[index_2].date)
              this.loadMarker('2')
            })
        }
        if (selectNum === '2') {
          this.PSV_sub.setPanorama(this.panorama[index_2].url, this.panorama[index_2].target)
            .then(() => {
              this.PSV_sub.setCaption(this.panorama[index_2].date)
              this.loadMarker('1')
              this.loadMarker('2')
            })
        }
      }).catch(err => {
        console.log(err)
      })
      // 获取标记数据
    }
  },
  components: {
    EditTooltilp
  },
  watch: {
    panoramaId(newVal, oldVal) {
      if (newVal) {
        this.getPanoramaData(newVal)
        this.PSV.resize({ width: 400, height: 360 })
        this.PSV_sub.resize({ width: 400, height: 360 })
      } else { }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.sphere-viewer {
  position: absolute;
  z-index: 99;
  top: 160px;
  left: 10px;
  width: 80vw;
  height: 560px;
  background: #ffffff;
  user-select: none;

  .sphere-viewer-close {
    position: absolute;
    top: 4px;
    right: 4px;
  }

  .viewer-container {
    display: flex;
    width: 100%;
    height: 100%;

    .container {
      width: 50%;

      .headerInfo {
        height: 40px;
        display: flex;
        /*垂直居中*/
        align-items: center;
        /*水平居中*/
        // justify-content: center;

        .title {
          margin-left: 10px;
          padding: 0 10px;
          // height: 100%;
          // // line-height: 100%;
          // display: inline-block;
        }
      }

      #viewer_1 {
        width: 100%;
        height: 100%;
      }

      #viewer_2 {
        width: 100%;
        height: 100%;
      }
    }
  }

  .el-select .el-input.is-focus .el-input__inner:focus,
  .el-select .el-input__inner:focus,
  .el-select .el-input.is-focus .el-input__inner {
    border-color: #c0c4cc;
  }
}
</style>